package com.putao.album.main;

import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.main.bean.NewPhotoItem;
import com.putao.album.main.view.FlipImageViewLayout;
import com.putao.album.popupwindow.PtThirdSharePopupWindow;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.UmengTouchEvent;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by chen on 15-6-17.
 */
public class ActivityNewPhotos extends BaseActivity {

    private ArrayList<NewPhotoItem> mDates = new ArrayList<NewPhotoItem>();
    private FlipImageViewLayout fl_view;
    private TextView title_tv, uploader;
    private Button back_btn, right_btn;
    private ImageView kiss, collection;
    private LinearLayout kiss_layout, collection_layout, share_layout;
    private PopupWindow mPopupWindow;
    private int curIndex = 0;

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_new_photos;
    }

    @Override
    public void doInitSubViews(View view) {
        back_btn = queryViewById(R.id.back_btn, true);
        title_tv = queryViewById(R.id.title_tv);
        uploader = queryViewById(R.id.uploader);
        right_btn = queryViewById(R.id.right_btn);
        right_btn.setBackgroundResource(R.color.transparent);


        fl_view = queryViewById(R.id.fl_view);
        fl_view.setonRemoveListener(new FlipImageViewLayout.OnRemoveListener() {
            @Override
            public void onRemoveEnd(int size) {
                if (size == 0) {
                    mActivity.finish();
                } else {
                    curIndex = mDates.size() - size;
                    Loger.d("chen++mDates.size()=" + mDates.size() + ",size=" + size);
                    updateUi();
                }
            }
        });

        kiss = queryViewById(R.id.kiss);
        collection = queryViewById(R.id.collection);

        kiss_layout = queryViewById(R.id.kiss_layout, true);
        collection_layout = queryViewById(R.id.collection_layout, true);
        share_layout = queryViewById(R.id.share_layout, true);

    }

    @Override
    public void doInitData() {
        getNewPhotos();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.kiss_layout:
                kissPhoto();
                break;
            case R.id.collection_layout:
                addOrCancelCollection();
                break;
            case R.id.share_layout:
                sharePhoto();
                break;
            default:
                break;
        }

    }

    /**
     * 亲照片
     */
    private void kissPhoto() {

        MobclickAgent.onEvent(mContext, UmengTouchEvent.KISS_PHOTO);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_id", mDates.get(curIndex).getPhoto_id());

        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_POST_PHOTO_PRAISE,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {

                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            String msg = json.getString("msg");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                kiss.setSelected(true);
                            }
                            showToast(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                    }
                });
    }

    private void addOrCancelCollection() {
        final NewPhotoItem curItem = mDates.get(curIndex);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_id", curItem.getPhoto_id());
        params.put("baby_id", curItem.getBaby_id());

        String url;
        if (curItem.getIs_choiceness() > 0) {
            url = PuTaoConstants.API_POST_PHOTO_DEL_CHOICENESS;
            MobclickAgent.onEvent(mContext, UmengTouchEvent.CANCEL_CHOICENESS);
        } else {
            url = PuTaoConstants.API_POST_PHOTO_ADD_CHOICENESS;
            MobclickAgent.onEvent(mContext, UmengTouchEvent.CHOICENESS);
        }

        HttpRequestUtil.doHttpPostRequest(mContext, url,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {

                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            String msg = json.getString("msg");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                if (curItem.getIs_choiceness() > 0) {
                                    curItem.setIs_choiceness(0);
                                    collection.setSelected(false);
                                } else {
                                    curItem.setIs_choiceness(1);
                                    collection.setSelected(true);
                                }
                                Bundle bundle = new Bundle();
                                EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_ADD_OR_REMOVE_COLLECTION, bundle));
                            }
                            showToast(msg);
                        } catch (JSONException e) {
                            showToast(getString(R.string.oprate_fail));
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        showToast(getString(R.string.oprate_fail));
                    }
                });

    }

    private void sharePhoto() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
            mPopupWindow = null;
        } else {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("baby_id", CommonUtils.getBabyId());

            params.put("photo_id", mDates.get(curIndex).getPhoto_id());

            final String url = mDates.get(curIndex).getPhoto();

            HttpRequestUtil.doHttpGetRequest(mActivity, PuTaoConstants.API_GET_SHARE_CONTENT,
                    new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                    new HttpRequestUtil.RequestResponseListener() {
                        @Override
                        public void success(int statuscode, String response) {
                            try {
                                JSONObject json = new JSONObject(response);
                                JSONObject data = json.getJSONObject("data");
                                String title = data.getString("title");

                                mPopupWindow = PtThirdSharePopupWindow.Create(mActivity, url, title, PtThirdSharePopupWindow.SHARE_PHOTO);
                                mPopupWindow.showAtLocation(share_layout, Gravity.BOTTOM, 0, 0);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void failed(int statuscode, String response) {
                            Loger.d("response:::" + response);
                        }
                    });
        }

    }

    private void updateUi() {
        NewPhotoItem curItem = mDates.get(curIndex);
        title_tv.setText(curItem.getBabyName() + "的新靓照");
        uploader.setText("by" + curItem.getUploader());
        right_btn.setText((curIndex + 1) + "/" + mDates.size());

        if (curItem.getIs_choiceness() > 0) {
            collection.setSelected(true);
        } else {
            collection.setSelected(false);
        }

        if (curItem.getIs_praise() > 0) {
            kiss.setSelected(true);
        } else {
            kiss.setSelected(false);
        }

    }

    private void getNewPhotos() {
        HashMap<String, String> params = new HashMap<String, String>();
        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_GET_NEW_PHOTOS,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)),
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {

                                json = new JSONObject(response);
                                String data = json.getString("data");
                                doAnalyzeDataList(new JSONObject(data));
                            } else {
                                showToast(HttpRequestUtil.getResponseErrorMsg(response));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        Loger.d("response:::" + response);
                    }
                });


    }

    private void doAnalyzeDataList(JSONObject data) {
        //{"data":[{"id":"1","name":"小华","birthday":"2012\/05\/22","sex":"M","create_uid":"661019",
        // "avatar":"http:\/\/file.cloud.putao.com\/b\/30\/b30b2f4c33d71a0689988da2ea705c083fde9d64_230x230.png",
        // "relationship":"妈妈"}],"status":"200"}
        mDates.clear();
        JSONArray list = data.optJSONArray("list");
        if (list != null) {
            for (int i = 0; i < list.length(); i++) {
                JSONObject o = null;
                try {
                    o = list.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (o != null) {
                    String uploader = o.optString("uploader");
                    String baby_id = o.optString("baby_id");
                    String babyName = o.optString("babyName");
                    JSONArray photo_list = o.optJSONArray("photo_list");

                    if (photo_list != null) {
                        for (int j = 0; j < photo_list.length(); j++) {
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = photo_list.getJSONObject(j);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            if (o != null) {
                                String photo_id = jsonObject.optString("photo_id");
                                String photo = jsonObject.optString("photo");
                                int is_praise = jsonObject.optInt("is_praise");
                                int is_choiceness = jsonObject.optInt("is_choiceness");

                                NewPhotoItem item = new NewPhotoItem();
                                item.setUploader(uploader);
                                item.setBaby_id(baby_id);
                                item.setBabyName(babyName);
                                item.setPhoto_id(photo_id);
                                item.setPhoto(photo);
                                item.setIs_praise(is_praise);
                                item.setIs_choiceness(is_choiceness);

                                mDates.add(item);
                            }

                        }
                    }
                }
            }


        }


        if (mDates.size() > 0) {
            kiss_layout.setClickable(true);
            collection_layout.setClickable(true);
            share_layout.setClickable(true);
            updateUi();
            initFImageDate();
            Loger.d("chen++mDates.size()=" + mDates.size());
        }
    }


    private void initFImageDate() {
        Loger.d("initFImageDate");
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < mDates.size(); i++) {
            list.add(mDates.get(i).getPhoto());
        }
        String[] urls = new String[list.size()];
        list.toArray(urls);
        fl_view.setImageUrls(urls);
    }
}
